package com.cskaoyan.market.controller;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.cskaoyan.market.bo.Register;
import com.cskaoyan.market.bo.Reset;
import com.cskaoyan.market.bo.UserInfo;
import com.cskaoyan.market.db.domain.MarketUser;
import com.cskaoyan.market.service.WxAuthService;

import com.cskaoyan.market.util.AdminResponseCode;
import com.cskaoyan.market.util.JacksonUtil;
import com.cskaoyan.market.util.ResponseUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.swing.text.html.FormSubmitEvent;
import javax.validation.Valid;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

@RestController
@RequestMapping("wx/auth")
public class WxAuthController {

    @Autowired
    WxAuthService wxAuthService;

    @Autowired
    SecurityManager securityManager;

    @PostMapping("register")
    public Object register(@RequestBody @Valid Register register) {
        int code = wxAuthService.register(register);
        // 插入成功后, 进行数据返回
        if (code == 200) {
            HashMap<String, Object> map = new HashMap<>();
            UserInfo userInfo = new UserInfo(register.getUsername(), "https://pic2.zhimg.com/v2-58ae90bcbd49421310edb66775812d3e_r.jpg");
            map.put("userInfo", userInfo);
            UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(register.getUsername(), register.getPassword());
            map.put("token", usernamePasswordToken);
            return ResponseUtil.ok(map);
            // 验证码错误
        } else if (code == AdminResponseCode.USER_CODE_ERROR) {
            return ResponseUtil.fail(AdminResponseCode.USER_CODE_ERROR, "验证码错误");
        } else if (code == AdminResponseCode.ROLE_USER_EXIST) {
            return ResponseUtil.fail(AdminResponseCode.ROLE_USER_EXIST, "用户已存在");
        }
        return ResponseUtil.badArgument();
    }

    @PostMapping("login")
    public Object login(@RequestBody Map<String, String> user, HttpServletRequest req, HttpServletResponse resp) {
        String username = user.get("username");
        String password = user.get("password");

        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
            return ResponseUtil.badArgument();
        }
        MarketUser user1 = wxAuthService.login(username, password);

        if (user1 == null) {
            //没有查找到数据，登录失败，用户名、密码错误
            return ResponseUtil.fail(700, "账号不存在");
        }

        String remoteAddr = req.getRemoteAddr();
        user1.setLastLoginIp(remoteAddr);
        user1.setLastLoginTime(LocalDateTime.now());
        wxAuthService.updateById(user1);

        Map<String, Object> result = new HashMap<>();
        Map<String, Object> userInfo = new HashMap<>();

        //userInfo
        userInfo.put("nickName", user1.getUsername());
        userInfo.put("avatarUrl", user1.getAvatar());
        //开始组装，userInfo
        result.put("userInfo", userInfo);
        //获取用户Id
        int id = wxAuthService.queryIdByUsername(username);
        //获取token
        SecurityUtils.setSecurityManager(securityManager);
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(username, password);
        subject.login(usernamePasswordToken);
        Session session = subject.getSession();
        session.setAttribute("id", id);
        result.put("token", session.getId());
        return ResponseUtil.ok(result);
    }

    @PostMapping("logout")
    public Object logout() {
        return ResponseUtil.ok();
    }


    @PostMapping("regCaptcha")
    public Object regCaptcha(@RequestBody String json, HttpSession session) {
        String mobile = JacksonUtil.parseString(json, "mobile");

        String accessKeyId = "LTAI5t8gpxPTCR6W58RnZq4u";
        String accessKeySecret = "mVPbpbxia0JQotb7HyJAREV8QUuq8h";
        //设定的签名名称
        String signName = "stone4j";
        //使用的模板名称：如下方，显示的固定字符即为模板里面的内容
        String templateCode = "SMS_173765187";
        //需要接收验证码的手机
        String phoneNumber = mobile;

        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
        // 使用 DefaultAcsClient 类构造函数创建并初始化一个 API 请求客户端
        // 它需要一个 DefaultProfile 对象来创建请求，因此要把第一步中创建的 profile 参数传递进去。
        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = new CommonRequest();
        request.setMethod(MethodType.POST);
        request.setDomain("dysmsapi.aliyuncs.com");
        request.setVersion("2017-05-25");
        request.setAction("SendSms");
        request.putQueryParameter("RegionId", "cn-hangzhou");
        request.putQueryParameter("PhoneNumbers", phoneNumber);
        request.putQueryParameter("SignName", signName);
        request.putQueryParameter("TemplateCode", templateCode);


        request.putQueryParameter("TemplateParam", "{\"code\":\"65536\"}");
        try {
            CommonResponse response = client.getCommonResponse(request);
            System.out.println(response.getData());
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return ResponseUtil.ok();
    }

    @PostMapping("reset")
    public Object reset(@RequestBody @Valid Reset reset) {
        int code = wxAuthService.reset(reset);
        if (code==200){
            return ResponseUtil.ok();
        }else if(code==AdminResponseCode.ROLE_USER_EXIST){
            return ResponseUtil.fail(AdminResponseCode.ROLE_USER_EXIST,"用户未找到");
        }else if(code==AdminResponseCode.USER_CODE_ERROR){
            return ResponseUtil.fail(AdminResponseCode.USER_CODE_ERROR,"验证码错误");

        }
        return ResponseUtil.badArgumentValue();
    }
}

